import 'dart:io';

import 'package:hrf_app/common/api/bug/bug.dart';
import 'package:hrf_app/common/models/bug/file_model.dart';
import 'package:hrf_app/common/models/bug/project_bug_file_model.dart';
import 'package:hrf_app/common/models/bug/project_bug_model.dart';
import 'package:hrf_app/common/models/bug/project_user_model.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_picker/Picker.dart';
import 'package:get/route_manager.dart';
import 'package:get/state_manager.dart';
import 'package:image_picker/image_picker.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';

class ProjectBugDetailPageController extends GetxController {
  ProjectBugDetailPageController();

  ProjectBugModel projectBugModel = ProjectBugModel();
  List<ProjectUserModel> projectUserList = [];
  List<UploadFileModel> uploadFileModelList = [];
  TextEditingController textEditController = TextEditingController();
  TextEditingController textSuspendController = TextEditingController();
  TextEditingController textActiveController = TextEditingController();

  _initData() {
    String id = Get.arguments;
    getPjProjectBugById(id);
    getPjProjectUserList();
  }

  getPjProjectBugById(id) async {
    List<UploadFileModel> uploadFileList = [];
    BugApi.getPjProjectBugByIdApi({"id": id}).then((res) {
      if (res["code"] == "00000") {
        projectBugModel = ProjectBugModel.fromJson(res["data"]);
        List<ProjectBugFileModel> fileList =
            projectBugModel.pjProjectBugFileVoList!;
        if (fileList.length != 0) {
          for (var vo in fileList) {
            UploadFileModel uploadFileModel = UploadFileModel();
            uploadFileModel.url = "/${vo.url!}";
            uploadFileList.add(uploadFileModel);
          }
        }
        uploadFileModelList = uploadFileList;
        update(["projectBugDetailPage"]);
      }
    });
  }

  Future<void> selectPhoto(ImageSource source) async {
    List<File> images = [];
    final picker = ImagePicker();
    final XFile? pickedFile = await picker.pickImage(source: source);
    if (pickedFile != null) {
      images.add(File(pickedFile.path));
    }
    uploadImg(images);
  }

  Future<void> selectMultiImage() async {
    List<File> images = [];
    final picker = ImagePicker();
    final List<XFile> pickedFileList = await picker.pickMultiImage();
    List<File> imageList = [];
    imageList = pickedFileList.map((file) => File(file.path)).toList();
      images.addAll(imageList);
    uploadImg(images);
  }

  Future<void> uploadImg(List<File> imgList) async {
    // 单个文件上传
    List<MultipartFile> multipartFile = [];
    for (var element in imgList) {
      MultipartFile mfile = await MultipartFile.fromFile(
        element.path,
      );
      multipartFile.add(mfile);
    }

    FormData formData = FormData.fromMap({'fileList': multipartFile});

    BugApi.simpleUploadListApi(formData).then((res) {
      if (res["code"] == "00000") {
        List<dynamic> imgUrlMap = res['data'];
        for (var itemVo in imgUrlMap) {
          UploadFileModel uploadFileModel = UploadFileModel();
          uploadFileModel.url = "/" + itemVo;
          uploadFileModelList.add(uploadFileModel);
        }
        TDToast.showSuccess("上传成功", context: Get.context!);
        update(["projectBugDetailPage"]);
      }
    });
  }

  @override
  void onReady() {
    _initData();
    super.onReady();
  }

  void delImage(index) {
    if (index >= 0 && index < uploadFileModelList.length) {
      uploadFileModelList.removeAt(index);
      update(["projectBugDetailPage"]);
    }
  }

  void editDialog(String content, String filedName, String title) {
    textEditController = TextEditingController(text: content);
    showGeneralDialog(
        context: Get.context!,
        pageBuilder: (BuildContext buildContext, Animation<double> animation,
            Animation<double> secondaryAnimation) {
          return TDInputDialog(
            textEditingController: textEditController,
            title: title,
            hintText: "请输入" + title,
            leftBtn: TDDialogButtonOptions(
                title: "取消",
                action: () {
                  Navigator.pop(Get.context!);
                }),
            rightBtn: TDDialogButtonOptions(
                title: "确定",
                action: () {
                  String aa = textEditController.text;
                  var parmas = {};
                  parmas["fieldName"] = filedName;
                  parmas["fieldValue"] = aa;
                  parmas["id"] = projectBugModel.id;
                  updateProjectBugSingle(parmas);
                }),
          );
        });
  }

  getPjProjectUserList() async {
    List<ProjectUserModel> userList = [];
    Map<String, dynamic> res = await BugApi.getPjProjectUserListApi({});
    for (var item in res["data"]) {
      userList.add(ProjectUserModel.fromJson(item));
    }
    projectUserList = userList;
  }

  //修改指派人
  updateUser(String userId) async {
    Map map = Map();
    map['assignUserId'] = userId;
    map['id'] = projectBugModel.id;
    Map<String, dynamic> res =
        await BugApi.updatePjProjectBugAssignUserIdApi(map);
    if (res["code"] == "00000") {
      getPjProjectBugById(projectBugModel.id);
      TDToast.showText('修改成功', context: Get.context!);
    }
  }

  void editAssignUserDialog(
      String content, String filedName, String title) async {
    Picker picket = Picker(
        adapter: PickerDataAdapter<String>(
            pickerdata: projectUserList.map((item) => item.realName).toList()),
        hideHeader: true);
    BuildContext? buildContext = Get.context!;
    Navigator.of(buildContext).push(TDSlidePopupRoute(
        slideTransitionFrom: SlideTransitionFrom.bottom,
        builder: (buildContext) {
          return TDPopupBottomConfirmPanel(
              title: "指派人 ",
              leftClick: () {
                Navigator.maybePop(buildContext);
              },
              rightClick: () {
                List<dynamic> value = picket.getSelectedValues();
                List<int> index = picket.selecteds;
                if (value.isEmpty) return;
                ProjectUserModel projectUserModel = projectUserList[index[0]];
                String userId = projectUserModel.userId!;

                updateUser(userId);
                Navigator.maybePop(buildContext);
              },
              child: picket.makePicker());
        }));
  }

  updateAssigneeId() {}

  updateProjectBugSingle(data) {
    BugApi.updatePjProjectBugSingleApi(data).then((res) => {
          Navigator.pop(Get.context!),
          TDToast.showSuccess('修改成功', context: Get.context!),
          getPjProjectBugById(projectBugModel.id),
        });
  }

  @override
  void onClose() {
    textEditController.dispose();
    textSuspendController.dispose();
    textActiveController.dispose();
    super.onClose();
  }

//暂停
  suspendProjectBug() {
    BuildContext buildContext = Get.context!;
    showGeneralDialog(
      context: buildContext,
      pageBuilder: (BuildContext buildContext, Animation<double> animation,
          Animation<double> secondaryAnimation) {
        return TDInputDialog(
          textEditingController: textSuspendController,
          title: "暂停原因",
          content: projectBugModel.title,
          hintText: "请输入暂停原因",
          rightBtn: TDDialogButtonOptions(
              title: "确定",
              action: () {
                String reason = textSuspendController.text;
                BugApi.suspendPjProjectBugApi({
                  "reason": reason,
                  "id": projectBugModel.id,
                }).then((res) {
                  TDToast.showSuccess('已暂停', context: Get.context!);
                  Navigator.pop(buildContext);
                  getPjProjectBugById(projectBugModel.id);
                });
              }),
        );
      },
    );
  }

//重启
  restartProjectBug() {
    BugApi.restartPjProjectBugApi({
      "id": projectBugModel.id,
    }).then((res) {
      TDToast.showSuccess('已重启', context: Get.context!);
      getPjProjectBugById(projectBugModel.id);
    });
  }

//解决
  solveProjectBug() {
    BugApi.solvePjProjectBugApi({
      "id": projectBugModel.id,
      "assignUserId": projectBugModel.assignUserId
    }).then((res) {
      TDToast.showSuccess('已解决', context: Get.context!);
      getPjProjectBugById(projectBugModel.id);
    });
  }

//关闭
  closeProjectBug() {
    BugApi.closePjProjectBugApi({"id": projectBugModel.id}).then((res) {
      TDToast.showSuccess('已关闭', context: Get.context!);
      getPjProjectBugById(projectBugModel.id);
    });
  }

//激活
  activeProjectBug() {
    BuildContext buildContext = Get.context!;
    showGeneralDialog(
      context: buildContext,
      pageBuilder: (BuildContext buildContext, Animation<double> animation,
          Animation<double> secondaryAnimation) {
        return TDInputDialog(
          textEditingController: textActiveController,
          title: "激活原因",
          content: projectBugModel.title,
          hintText: "请输入激活原因",
          rightBtn: TDDialogButtonOptions(
              title: "确定",
              action: () {
                String reason = textActiveController.text;
                BugApi.activePjProjectBugApi(
                        {"id": projectBugModel.id, "activeReason": reason})
                    .then((res) {
                  TDToast.showSuccess('已激活', context: Get.context!);

                  Navigator.pop(Get.context!);
                  getPjProjectBugById(projectBugModel.id);
                });
              }),
        );
      },
    );
  }
}
